# -*- coding: utf-8 -*-
# Copyright © 2017 Beijing HengXingChangDa Technology Co., Ltd. All rights reserved.

from utils.reqres import *
from django.db import models, transaction, IntegrityError
from django.core.exceptions import ValidationError
from utils.reqres import *
import requests
from mjs.config import *
from .models import CSMUser
import json
from proto.csm import *


def user_info(user):
    # https://csm.dcclouds.com/NimsoftServiceDesk/servicedesk/odata/Contact?&$filter=MdrElementID%20gt%200&&
    # %24orderby=FirstName%20asc%2CFamilyName%20asc%2CEmailAddress%20asc%2CUserLogin%20asc%2CUserLicenseType%20asc%2CUserOrgList%20asc%2CUserRoleList%20asc%2CUserGroupList%20asc&
    # %24inlinecount=allpages

    url = '{server}/NimsoftServiceDesk/servicedesk/odata/Contact'.format(server=CSM_SERVER)
    params = list()
    params.append(('fetchrelatedentitynames', 'true'))
    # params.append(('$select', 'MdrElementID,MdrProdInstance,MdrProduct'))

    params.append(('$select', 'MdrElementID, MdrProdInstance, MdrProduct, ExternalUserID, FirstName, MiddleName, FamilyName, EmailAddress, UserLogin, UserType, UserLicenseType, UserLicenseTypeCode, IsLoginEnabled, NonTranslatedIsLoginEnabled, NameTitle, JobTitle, IsVIP, NonTranslatedIsVIPEnabled, IsOutOfOffice, DeputyUserName, DeputyID, PrimaryPhone, Locale, LanguageKey, DateTimeFormatRegion, ContactStatus, NonTranslatedContactStatus, LinkedInUrl, ContactTimezone, CreationTimestamp, CreationUserName, LastModTimestamp, LastModUserName, Department, Location, PinNumber, ExcludeFromSurveys, PhoneType2, Phone2, PhoneType3, Phone3, PhoneType4, Phone4, EmployeeID, SourceKey, NotificationMechanism, PagerType, PageEmail, ManagerUserName, ManagerID, BusinessSegment, ManagedBusinessUnit, ManagedFunction, ManagedEntity, HRGeneralistUserName, HRGeneralistID, ContractorUserName, ContractorID, StartDate, EndDate, OtherInformation, UserOrgList, UserGroupList, UserRoleList, PrimaryOrganizationID'))
    params.append(('removeParentEntityIfNoExpand', 'true'))
    # params.append(('$orderby', 'LastModTimestamp desc'))
    params.append(('$format', 'json'))
    params.append(('$skip', '0'))
    params.append(('$top', '10000'))
    # params.append(('CTGREQUEST', 'TRUE'))
    # params.append(('_dc', '1504059926934'))
    # params.append(('INClause', 'AssignedGroupID~~-1,34,31,30,11,2,1'))
    params.append(('$inlinecount', 'allpages'))
    cookies = user.getCookie()
    res = requests.get(url, params=tuple(params), cookies=cookies)
    if res.status_code == requests.codes.ok:
        # print res.url
        # print res.text
        csmres = res.json()
        # print csmres
    else:
        # print res.url
        # print res.status_code
        res.raise_for_status()


def user_context(user):
    url = '{server}/NimsoftServiceDesk/servicedesk/odata/getUserinitContext'.format(server=CSM_SERVER)
    params = list()
    params.append(('$format', 'json'))
    cookies = user.getCookie()
    res = requests.get(url, params=tuple(params), cookies=cookies)
    if res.status_code == requests.codes.ok:
        csmres = json.loads(res.json()['d']['JSONData'])
        csmres = csmres[0]
        csmu = csmres['contactInfo']
        user.email = csmu['EmailAddress']
    else:
        # print res.url
        # print res.status_code
        res.raise_for_status()


def user_login(username="liuzong@wechatdemo.com", password="Test@1234"):
    new_user = True
    qs = CSMUser.get_all().filter(username=username)
    if qs:
        user = qs[0]
        new_user = False

    csmres, cookies = csm_user_login(username, password)
    slice_id = csmres['external_slice']
    user_id = csmres['external_user_id']
    firstname = csmres['first_Name']
    lastname = csmres['last_Name']
    try:
        with transaction.atomic():
            if new_user:
                user = CSMUser()
            user.token = user_id
            user.firstname = firstname
            user.lastname = lastname
            user.username = username
            user.password = password
            user.csm_slice_id = slice_id
            user.csm_user_id = user_id
            user.setCookie(cookies)
            # user_info(user)
            user_context(user)
            user.save()
    except IntegrityError as e:
        kerror(e)
        raise
    except ValidationError as e:
        kerror(e)
        raise
    else:
        return user


def handle_login(req):
    req = get_request(req, 'POST')
    if 'username' not in req \
            or 'password' not in req:
        return BadRequest()
    username = req.get('username', 'zhaosi@2001.com')
    password = req.get('password', 'Test@1234')

    user = user_login(username, password)
    return HttpResponse(user.token)


# def handle_list(req):
#     cookies = get_cookie(req)
#     req = get_request(req, 'GET')
#
#     sid = req.get('sid', "fb76c1a6-9824-41f6-9509-44bcb7d1ad2a")
#     uid = req.get('uid', "21")
#     # $filter=((NonTranslatedTicketStatus ne 'Archive' and NonTranslatedTicketStatus ne 'Request - Delete' and NonTranslatedTicketStatus ne 'Closed') and (OrgStatus eq 0))&
#     # INClause=AssignedGroupID~~-1,34,31,30,11,2,1&
#     # $select=AssignedCaseID,AssignedID,TypeName,Priority,SLAResolveByTimestamp,SLAComplianceStatus,TranslatedTypeName,TranslatedSLAComplianceStatus,CreationTimestamp,LastModTimestamp,Description,RequesterVIPFlag,RequesterUserName,RequesterOrgName,RequestedForUserName,RequestedForOrgName,RequesterOrgHierarchicalPath,RequesterRootOrgName,TicketStatus,ReasonCode,AssignedIndividual,AssignedGroup,MdrElementID,LockedByExternalUserId,CategorizationClass,CategorizationCategory,CategorizationType,CategorizationItem,HasAttachments&
#     # categorytype=list&
#     # CTGREQUEST=TRUE&
#     # _dc=1504059926934&
#     # $format=json&$skip=0&$top=25&
#     # $orderby=LastModTimestamp desc&
#     # $inlinecount=allpages
#     url = '{server}/NimsoftServiceDesk/{sid}/servicedesk/odata/Ticket'.format(server=COWS_SERVER, sid=sid)
#     params = list()
#     params.append(('$filter', "((RequesterID eq '{uid}' or RequestedForID eq '{uid}') and (NonTranslatedTicketStatus ne 'Archive' and NonTranslatedTicketStatus ne 'Request - Delete' and NonTranslatedTicketStatus ne 'Closed') and (OrgStatus eq 0))".format(uid=uid)))
#     # params.append(('$select', 'AssignedCaseID,AssignedID,TypeName,Priority,SLAResolveByTimestamp,SLAComplianceStatus,TranslatedTypeName,TranslatedSLAComplianceStatus,CreationTimestamp,LastModTimestamp,Description,RequesterVIPFlag,RequesterUserName,RequesterOrgName,RequestedForUserName,RequestedForOrgName,RequesterOrgHierarchicalPath,RequesterRootOrgName,TicketStatus,ReasonCode,AssignedIndividual,AssignedGroup,MdrElementID,LockedByExternalUserId,CategorizationClass,CategorizationCategory,CategorizationType,CategorizationItem,HasAttachments'))
#     params.append(('$select','Priority,TranslatedTypeName,RequesterUserName,LastModTimestamp,Description,TicketStatus,ReasonCode,MdrElementID'))
#     params.append(('$orderby', 'LastModTimestamp desc'))
#     params.append(('$format', 'json'))
#     params.append(('$skip', '0'))
#     params.append(('$top', '10000'))
#     params.append(('categorytype', 'list'))
#     # params.append(('CTGREQUEST', 'TRUE'))
#     # params.append(('_dc', '1504059926934'))
#     # params.append(('INClause', 'AssignedGroupID~~-1,34,31,30,11,2,1'))
#     params.append(('$inlinecount', 'allpages'))
#
#     res = requests.get(url, params=tuple(params), cookies=cookies)
#     if res.status_code == requests.codes.ok:
#         # print res.url
#         # print res.text
#         csmres = res.json()
#         tickets = list()
#         for csmt in csmres['d']['results']:
#             # print csmt
#             t = Ticket()
#             t.Priority = csmt['Priority']
#             t.desc = csmt['Description']
#             t.category = csmt['TranslatedTypeName']
#             t.status = csmt['ReasonCode']
#             t.status = csmt['TicketStatus']
#             t.mdrid = csmt['MdrElementID']
#             t.mpiid = csmt['MdrProdInstance']
#             t.mpid = csmt['MdrProduct']
#             t.username = csmt['RequesterUserName']
#             t.lastupdate = csmt['LastModTimestamp']
#             # print t
#             tickets.append(t)
#     else:
#         print res.url
#         print res.status_code
#         res.raise_for_status()
#
#     return handle_result(Ticket, req, tickets, detail=False)
#
#
# def handle_info(req):
#     # print req.COOKIES
#
#     cookies = get_cookie()
#     sid = "fb76c1a6-9824-41f6-9509-44bcb7d1ad2a"
#     MdrElementID = '207'
#     MdrProdInstance = '1100001'
#     MdrProduct = 'CA:00050'
#     url = "{server}/NimsoftServiceDesk/{sid}/servicedesk/odata/Ticket(MdrElementID='{MdrElementID}',MdrProdInstance='{MdrProdInstance}',MdrProduct='{MdrProduct}')".format(server=COWS_SERVER,
#                                                                                    sid=sid,MdrElementID=MdrElementID,MdrProdInstance=MdrProdInstance,MdrProduct=MdrProduct)
#     params = list()
#     # params.append(('$filter',
#     #                "((NonTranslatedTicketStatus ne 'Archive' and NonTranslatedTicketStatus ne 'Request - Delete' and NonTranslatedTicketStatus ne 'Closed') and (OrgStatus eq 0))"))
#     # params.append(('$select',
#     #                'AssignedCaseID,AssignedID,TypeName,Priority,SLAResolveByTimestamp,SLAComplianceStatus,TranslatedTypeName,TranslatedSLAComplianceStatus,CreationTimestamp,LastModTimestamp,Description,RequesterVIPFlag,RequesterUserName,RequesterOrgName,RequestedForUserName,RequestedForOrgName,RequesterOrgHierarchicalPath,RequesterRootOrgName,TicketStatus,ReasonCode,AssignedIndividual,AssignedGroup,MdrElementID,LockedByExternalUserId,CategorizationClass,CategorizationCategory,CategorizationType,CategorizationItem,HasAttachments'))
#     # params.append(('$orderby', 'LastModTimestamp desc'))
#     params.append(('$format', 'json'))
#     # params.append(('$skip', '0'))
#     # params.append(('$top', '25'))
#     params.append(('categorytype', 'list'))
#     params.append(('parent_entity_key', MdrElementID))
#     params.append(('fetch_for_related_tickets', 'false'))
#     params.append(('fetch_for_related_cis', 'false'))
#     params.append(('fetch_for_related_ci', 'false'))
#     params.append(('recentactivity', 'true'))
#     params.append(('archived', 'no'))
#     # params.append(('CTGREQUEST', 'TRUE'))
#     # params.append(('_dc', '1504059926934'))
#     # params.append(('INClause', 'AssignedGroupID~~-1,34,31,30,11,2,1'))
#     # params.append(('$inlinecount', 'allpages'))
#
#     res = requests.get(url, params=tuple(params), cookies=cookies)
#     if res.status_code == requests.codes.ok:
#         print res.url
#         print res.text
#     else:
#         print res.url
#         print res.status_code
#         res.raise_for_status()
#
#     return HttpResponse("test")
#
#
# def handle_set(req):
#     return HttpResponse("test")
#
#
# def handle_add(req):
#     cookies = get_cookie()
#     sid = "fb76c1a6-9824-41f6-9509-44bcb7d1ad2a"
#     MdrElementID = '207'
#     MdrProdInstance = '1100001'
#     MdrProduct = 'CA:00050'
#     # url = "{server}/NimsoftServiceDesk/{sid}/servicedesk/odata/Ticket(MdrElementID='{MdrElementID}',MdrProdInstance='{MdrProdInstance}',MdrProduct='{MdrProduct}')".format(server=COWS_SERVER,sid=sid,MdrElementID=MdrElementID,MdrProdInstance=MdrProdInstance,MdrProduct=MdrProduct)
#     url = "{server}/NimsoftServiceDesk//servicedesk/odata/ServiceRequest".format(server=COWS_SERVER)
#     params = list()
#     # params.append(('$filter',
#     #                "((NonTranslatedTicketStatus ne 'Archive' and NonTranslatedTicketStatus ne 'Request - Delete' and NonTranslatedTicketStatus ne 'Closed') and (OrgStatus eq 0))"))
#     # params.append(('$select',
#     #                'AssignedCaseID,AssignedID,TypeName,Priority,SLAResolveByTimestamp,SLAComplianceStatus,TranslatedTypeName,TranslatedSLAComplianceStatus,CreationTimestamp,LastModTimestamp,Description,RequesterVIPFlag,RequesterUserName,RequesterOrgName,RequestedForUserName,RequestedForOrgName,RequesterOrgHierarchicalPath,RequesterRootOrgName,TicketStatus,ReasonCode,AssignedIndividual,AssignedGroup,MdrElementID,LockedByExternalUserId,CategorizationClass,CategorizationCategory,CategorizationType,CategorizationItem,HasAttachments'))
#     # params.append(('$orderby', 'LastModTimestamp desc'))
#     params.append(('$format', 'json'))
#     # params.append(('$skip', '0'))
#     # params.append(('$top', '25'))
#     params.append(('categorytype', 'list'))
#     params.append(('parent_entity_key', MdrElementID))
#     params.append(('fetch_for_related_tickets', 'false'))
#     params.append(('fetch_for_related_cis', 'false'))
#     params.append(('fetch_for_related_ci', 'false'))
#     params.append(('recentactivity', 'true'))
#     params.append(('archived', 'no'))
#     # params.append(('CTGREQUEST', 'TRUE'))
#     # params.append(('_dc', '1504059926934'))
#     # params.append(('INClause', 'AssignedGroupID~~-1,34,31,30,11,2,1'))
#     # params.append(('$inlinecount', 'allpages'))
#
#
#
#     res = requests.get(url, params=tuple(params), cookies=cookies)
#     if res.status_code == requests.codes.ok:
#         print res.url
#         print res.text
#     else:
#         print res.url
#         print res.status_code
#         res.raise_for_status()
#
#     return HttpResponse("test")
#
#
# def handle_del(req):
#     return HttpResponse("test")

